#!/bin/sh
#
# ssh -- login the docker lab via ssh
#
# Copyright (C) 2016-2021 Wu Zhangjin <falcon@ruma.tech>
#

TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd)"
. "$TOP_DIR"/tools/docker/config >/dev/null

prepare_login || exit 0

log_print "Get cached data"
get_vars UNIX_PWD UNIX_USER VNC_IP
get_host

which sshpass >/dev/null 2>&1
[ $? -eq 0 ] && SSH_PASS="sshpass -p '$UNIX_PWD'"

if [ "x$HOST_OS" != "xWindows" ]; then
  SSH_X=-X
else
  WINPTY="winpty"
fi

IP=$VNC_IP
SSH_PORT=$CONTAINER_SSH_PORT

SSH_CMD="$WINPTY $SSH_PASS ssh $SSH_X -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -t ${UNIX_USER}@${IP} -p ${SSH_PORT} 'cd $LAB_WORKDIR/$CURRENT && exec bash -l'"

if [ -z "$SSH_PASS" ]; then
  echo
  log_print "Password '$UNIX_PWD' required, please login with the following command:"
  echo
  echo "  $SSH_CMD"
  echo

  log_print "If want to login without password, there are two methods:"
  echo
  echo "  1. Install the 'sshpass' command"
  echo

  cat <<EOF
  2. Upload public ssh key with following steps:

        $ mkdir ~/.ssh/
        $ touch ~/.ssh/authorized_keys
        $ chmod 700 ~/.ssh/
        $ chmod 644 ~/.ssh/authorized_keys
        $ vim ~/.ssh/authorized_keys

        Generate a public ssh key with 'ssh-keygen'
        Copy your public ssh key and paste it into the ~/.ssh/authorized_key

EOF

fi

if [ "x$HOST_OS" != "xWindows" ]; then
  echo
  log_print "Enable X11 Forwarding support"
  echo

  which xhost >/dev/null 2>&1
  [ $? -eq 0 ] && xhost +

  cat <<EOF > ~/.ssh/ssh-x11-forward.config
# X11 Forwarding Support
Host *
   ForwardAgent yes
   ForwardX11 yes
   ForwardX11Trusted yes
EOF

fi

echo
log_print "Running '$SSH_CMD'"
echo

eval "$SSH_CMD"
